var express = require('express');
var app = express();
let port = 8001
const { firefox } = require('playwright');
const dayjs=require('dayjs')
// 创建队列类
class RequestQueue {
    constructor(maxConcurrent) {
        this.maxConcurrent = maxConcurrent;
        this.currentRequests = 0;
        this.queue = [];
    }
    // 添加请求到队列
    enqueue(req, res, next) {
        if (this.currentRequests < this.maxConcurrent) {
            this.currentRequests++;
            next();
        } else {
            var url = req.protocol + '://' + req.hostname + req.originalUrl;
            // console.log("服务器繁忙",url)
            res.redirect(url)
        }
    }
    // 释放资源
    dequeue() {
        this.currentRequests--;
        if (this.queue.length > 0) {
            const { req, res, next } = this.queue.shift();
            this.currentRequests++;
            next();
        }
    }
}
// 创建队列实例，最大并发数设为1
const requestQueue = new RequestQueue(1);
// 中间件
const limitConcurrent = (req, res, next) => {
    requestQueue.enqueue(req, res, next);
};
// 使用中间件
app.use(limitConcurrent);
// 释放资源
app.use((req, res, next) => {
    res.on('finish', () => {
        requestQueue.dequeue();
    });
    next();
});
app.get('/',async (req, res) => {
    // 部署到服务器的完整URL
    // var url = req.protocol + '://' + req.hostname + req.originalUrl;
    let url = req.query.url
    console.log(url,"asdasdasd")
    const browser = await firefox.launch({
        headless: true,
    });
    const page = await browser.newPage();
    page.setDefaultTimeout(10000)
    page.goto(url).then(result => {
        setTimeout(async () => {
            let content = await page.content()
            page.close()
            browser.close()
            res.send(content)
            console.log(`成功,${url},${dayjs().format("YYYY-MM-DD HH:mm:ss")}`)
        }, 2000)
    }).catch(async error => {
        // 访问出错,关闭浏览器,重定向至目标页面
        console.log(`失败,${url},${dayjs().format("yyyy-MM-DD HH:mm:ss")}`)
        page.close()
        browser.close()
        res.redirect(url)
    })
});
const server = app.listen(port, '0.0.0.0', () => {
    console.log('Spider app listening on port ' + port + '!');
});
server.on('error', (err) => {
    console.error('端口绑定错误：', err);
    // 发生错误时退出进程，避免容器假运行
    process.exit(1);
});